const express = require('express');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const mysql = require('mysql2');
const { log } = require('console');

const app = express();
app.use(bodyParser.json());

const secretKey = 'your_secret_key';

// 数据库连接
const db = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'admin123',
    database: 'attendance_db'
});

db.connect((err) => {
    if (err) throw err;
    console.log('Connected to database');
});

app.get('/getinfo', (req, res) => res.send('Hello World!'));

// 用户注册
app.post('/register', (req, res) => {
    const { username, password } = req.body;
    bcrypt.hash(password, 10, (err, hash) => {
        if (err) throw err;
        const sql = 'INSERT INTO users (username, password) VALUES (?, ?)';
        db.query(sql, [username, hash], (err, result) => {
            if (err) throw err;
            res.send({ message: 'User registered' });
        });
    });
});

// 用户登录
app.post('/login', (req, res) => {
    const { username, password } = req.body;
    console.log(req.body);
    const sql = 'SELECT * FROM users WHERE username = ?';
    db.query(sql, [username], (err, results) => {
        if (err) throw err;
        if (results.length === 0) {
            return res.status(400).send({ message: 'User not found' });
        }
        // 直接对比明文密码
        if (password !== results[0].password) {
            return res.status(400).send({ message: 'Invalid password' });
        }
        const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
        res.send({ token });
    });
});


// 签到
app.post('/sign-in', (req, res) => {
    const token = req.headers['authorization'].split(' ')[1];
    jwt.verify(token, secretKey, (err, decoded) => {
        if (err) return res.status(401).send({ message: 'Unauthorized' });
        const username = decoded.username;
        console.log(username);
        const sql = 'INSERT INTO records (username, time) VALUES (?, NOW())';
        db.query(sql, [username], (err, result) => {
            if (err) throw err;
            res.send({ message: 'Sign-in recorded' });
        });
    });
});


const port = 3001;
app.listen(port, () => {
    console.log(`Server running on http://127.0.0.1:${port}`);
});
